﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Input;

using WallpaperEngineLib;

using WpfApp4.Library;
using WpfApp4.Models;
using WpfApp4.Models.Caches;
using WpfApp4.Models.Config;
using WpfApp4.Utilities;
using WpfApp4.Views;

using XEvent;
using XEvent.Events;
using XEvent.UI;


namespace WpfApp4.ViewModels
{
    public class MainWindowViewModel : ViewModelBase
    {
        private WindowEvent _windowEvent;
        private Process _currentProcess;
        private PlayerWindow _currentPlayer;


        public MainWindowViewModel()
        {
            _windowEvent = XEventAgent.Instance.EventManager.GetEvent<WindowEvent>();

            WindowWidth = ApplicationConfigSetting.DefaultWidth;
            WindowHeight = ApplicationConfigSetting.DefaultHeight;
        }

        #region Windows Property

        private int _windowWidth;
        public int WindowWidth { get => _windowWidth; set => SetProperty(ref _windowWidth, value); }

        private int _windowHeight;
        public int WindowHeight { get => _windowHeight; set => SetProperty(ref _windowHeight, value); }

        #endregion

        #region Urls

        #endregion

        #region Commands

        #region 工具箱

        /// <summary>
        /// 更新地址（已淘汰）
        /// </summary>
        public ICommand UpdateUrlCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var url = config.CommandParameter;
                var windowSize = Utilities.Utility.GetWindowSize(config);
                WindowWidth = windowSize.Width;
                WindowHeight = windowSize.Height;

                _windowEvent.Publish(new WindowEvent
                {
                    Data = url,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Update,
                    EventId = EventId.UpdateUrl,
                });
            });
        }

        public ICommand OpenUrlCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var url = config.CommandParameter;
                var windowSize = Utility.GetWindowSize(config);
                switch (config.OpenModel)
                {
                    case OpenModel.CurrentWindow:
                        {
                            WindowWidth = windowSize.Width;
                            WindowHeight = windowSize.Height;

                            _windowEvent.Publish(new WindowEvent
                            {
                                Data = url,
                                Type = EventType.Action,
                                WindowActionType = WindowActionType.Update,
                                EventId = EventId.UpdateUrl,
                            });
                        }
                        break;
                    case OpenModel.NewWindow:
                        {
                            var browse = XEvent.Ioc.XContainerLocator.Instance.Resolve<BrowseWindow>("browse");
                            browse.body.Width = windowSize.Width;
                            browse.body.Height = windowSize.Height;
                            browse.webView.Source = new Uri(url);

                            WindowManager.Instance.Add(url, browse);

                            _windowEvent.Publish(new WindowEvent
                            {
                                Data = browse,
                                Type = EventType.Action,
                                WindowActionType = WindowActionType.Open,
                                EventId = EventId.OpenBrowseWindow,
                            });
                        }
                        break;
                }
            });
        }


        /// <summary>
        /// 打开地址栏窗口
        /// </summary>
        public ICommand OpenUrlInputCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                Action action = () =>
                {
                    var urlConfig = config.Clone();
                    urlConfig.CommandParameter = ApplicationConfigSetting.CurrentUrl;
                    OpenUrlCommand.Execute(urlConfig);
                };

                _windowEvent.Publish(new WindowEvent
                {
                    CallBack = action,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Edit,
                    EventId = EventId.OpenUrlWindow,
                });
            });
        }

        public ICommand OpenFileWindowCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                Action action = () =>
                {
                    var inputData = CommonCache.Instance.Get("input");
                };

                _windowEvent.Publish(new WindowEvent
                {
                    CallBack = action,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Open,
                    EventId = EventId.OpenInputBox,
                });
            });
        }

        /// <summary>
        /// 搜索指令
        /// </summary>
        public ICommand SearchCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                Action action = () =>
                {
                    string inputData = (string)CommonCache.Instance.Get("input");
                    string url;
                    MenuConfig urlConfig = config.Clone();
                    //urlConfig.OpenModel = OpenModel.NewWindow;

                    string pattern = @"^(((ht|f)tps?):\/\/)?([^!@#$%^&*?.\s-]([^!@#$%^&*?.\s]{0,63}[^!@#$%^&*?.\s])?\.)+[a-z]{2,6}\/?";
                    
                    if (Regex.IsMatch(inputData, pattern))
                    {
                        if (!inputData.StartsWith("http://") || !inputData.StartsWith("https://"))
                        {
                            if (!inputData.StartsWith("www."))
                            {
                                inputData = "http://" + inputData;
                            }
                            else
                            {
                                inputData = "http://" + inputData;
                            }
                        }
                        url = inputData;
                    }
                    else
                    {
                        url = "https://www.baidu.com/s?ie=utf-8&wd=" + inputData;
                    }

                    urlConfig.CommandParameter = url;
                    OpenUrlCommand.Execute(urlConfig);
                };

                _windowEvent.Publish(new WindowEvent
                {
                    CallBack = action,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Open,
                    EventId = EventId.OpenInputBox,
                });
            });
        }

        public ICommand CloseBrowserWindowCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var window = WindowManager.Instance.GetWindow(config.Name);
                WindowManager.Instance.Remove(window);
                window.Close();
            });
        }

        /// <summary>
        /// 更新菜单
        /// </summary>
        public ICommand RefreshMenuCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                _windowEvent.Publish(new WindowEvent
                {
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Update,
                    EventId = EventId.RefreshMenu,
                });
            });
        }

        /// <summary>
        /// 打开窗口
        /// </summary>
        public ICommand OpenWindowCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                string winName = config.CommandParameter;
                if (string.IsNullOrEmpty(winName.Trim()))
                {
                    return;
                }

                var window = XEvent.Ioc.XContainerLocator.Instance.Resolve<Window>(winName);
                _windowEvent.Publish(new WindowEvent
                {
                    Data = window,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Open,
                    EventId = EventId.SettingWindow,
                });
            });
        }

        /// <summary>
        /// 退出
        /// </summary>
        public ICommand ExitAppCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                _windowEvent.Publish(new WindowEvent
                {
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Close,
                    EventId = EventId.ExitApplication,
                });
            });
        }


        #endregion

        #region 文件

        /// <summary>
        /// 打开配置
        /// </summary>
        public ICommand OpenConfigCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Config", "menu.json");

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "C:\\Users\\xianglingyue\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe", // VSCode的CLI命令通常是"code"
                    Arguments = $"\"{configPath}\"", // 文件路径作为参数
                    UseShellExecute = false, // 不使用操作系统外壳启动进程
                    CreateNoWindow = true, // 不创建新窗口
                    WindowStyle = ProcessWindowStyle.Hidden, // 窗口风格设置为隐藏
                };

                Process.Start(startInfo);
            });
        }

        /// <summary>
        /// 打开文件（通过VSCode打开）
        /// </summary>
        public ICommand OpenFileByVSCodeCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var configPath = config.CommandParameter;
                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "C:\\Users\\xianglingyue\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe", // VSCode的CLI命令通常是"code"
                    Arguments = $"\"{configPath}\"", // 文件路径作为参数
                    UseShellExecute = false, // 不使用操作系统外壳启动进程
                    CreateNoWindow = true, // 不创建新窗口
                    WindowStyle = ProcessWindowStyle.Hidden, // 窗口风格设置为隐藏
                };

                Process.Start(startInfo);
            });
        }

        /// <summary>
        /// 打开文件（通过记事本打开）
        /// </summary>
        public ICommand OpenFileCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var configPath = config.CommandParameter;

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    FileName = "notepad.exe", // VSCode的CLI命令通常是"code"
                    Arguments = $"\"{configPath}\"", // 文件路径作为参数
                    UseShellExecute = false, // 不使用操作系统外壳启动进程
                    CreateNoWindow = true, // 不创建新窗口
                    WindowStyle = ProcessWindowStyle.Hidden, // 窗口风格设置为隐藏
                };

                Process.Start(startInfo);
            });
        }

        #endregion

        #region 窗口

        /// <summary>
        /// 更新窗口尺寸
        /// </summary>
        public ICommand UpdateWindowSizeCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var size = config.CommandParameter;
                WindowWidth = Convert.ToInt32(size.Split('*')[0].Trim());
                WindowHeight = Convert.ToInt32(size.Split('*')[1].Trim());
            });
        }


        #endregion

        #region 壁纸

        /// <summary>
        /// 设置壁纸
        /// </summary>
        public ICommand SetWallpaperCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                Action<string> action = (url) =>
                {
                    if (_currentPlayer == null)
                    {
                        _currentPlayer = new PlayerWindow();
                    }
                    _currentPlayer.Show();
                    //WallpaperEngine.Instance.SetWallpaper(_currentPlayer);
                    _currentPlayer.UpdateUrl(url);
                };
                _windowEvent.Publish(new WindowEvent
                {
                    CallBack = action,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.OK,
                    EventId = EventId.GetCurrentUrl,
                });
            });
        }

        /// <summary>
        /// 应用壁纸
        /// </summary>
        public ICommand ApplyWallpaper
        {
            get => new RelayCommand<object>(obj =>
            {
                if (_currentPlayer == null)
                {
                    SetWallpaperCommand.Execute(null);
                }

                _currentPlayer.Left = 0;
                _currentPlayer.Top = 0;
                _currentPlayer.Width = SystemParameters.PrimaryScreenWidth;
                _currentPlayer.Height = SystemParameters.PrimaryScreenHeight;

                WallpaperEngine.Instance.SetWallpaper(_currentPlayer);
            });
        }

        /// <summary>
        /// 编辑壁纸
        /// </summary>
        public ICommand SettingWallpaperCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                if (_currentPlayer != null)
                {
                    _currentPlayer.Width = 480;
                    _currentPlayer.Height = 270;
                    _currentPlayer.Left = (SystemParameters.PrimaryScreenWidth / 2) - (270 / 2);
                    _currentPlayer.Top = (SystemParameters.PrimaryScreenHeight / 2) - (480 / 2);

                    WallpaperEngine.Instance.TopWindow(_currentPlayer);
                }
            });
        }

        /// <summary>
        /// 退出壁纸
        /// </summary>
        public ICommand ExitWallpaperCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                if (_currentPlayer != null)
                {
                    _currentPlayer.Close();
                    _currentPlayer = null;
                }
            });
        }

        #endregion

        #region 进程

        public ICommand OpenApplicationCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var proc = config.CommandParameter;
                if (string.IsNullOrEmpty(proc))
                {
                    return;
                }

                Process process = new Process();
                process.StartInfo = new ProcessStartInfo(proc);
                process.Start();
            });
        }


        /// <summary>
        /// Excel转Json（不支持使用）
        /// </summary>
        public ICommand ExcelToJsonCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var proc = config.CommandParameter;
                if (string.IsNullOrEmpty(proc))
                {
                    return;
                }

                Action action = () =>
                {
                    string inputData = (string)CommonCache.Instance.Get("input");
                    if (string.IsNullOrEmpty(inputData)) return;

                    try
                    {
                        ProcessStartInfo startInfo = new ProcessStartInfo
                        {
                            FileName = proc,
                            Arguments = $"\"{inputData}\"", // 文件路径作为参数
                            UseShellExecute = false, // 不使用操作系统外壳启动进程
                            CreateNoWindow = true, // 不创建新窗口
                            WindowStyle = ProcessWindowStyle.Hidden, // 窗口风格设置为隐藏
                        };
                        Process.Start(startInfo);

                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }

                };

                _windowEvent.Publish(new WindowEvent
                {
                    CallBack = action,
                    Type = EventType.Action,
                    WindowActionType = WindowActionType.Open,
                    EventId = EventId.OpenInputBox,
                });
            });
        }


        /// <summary>
        /// 打开进程
        /// </summary>
        public ICommand StartProcessCommand
        {
            get => new RelayCommand<MenuConfig>(config =>
            {
                var proc = config.CommandParameter;
                if (string.IsNullOrEmpty(proc))
                {
                    return;
                }

                if (_currentProcess != null)
                {
                    _currentProcess.Kill();
                    _currentProcess = null;
                }
                _currentProcess = new Process();
                _currentProcess.StartInfo = new ProcessStartInfo(proc);
                _currentProcess.Start();
            });
        }

        /// <summary>
        /// 关闭进程
        /// </summary>
        public ICommand ExitProcessCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                if (_currentProcess != null)
                {
                    _currentProcess.Kill();
                    _currentProcess = null;
                }
            });
        }


        #endregion


        #endregion

        #region 协程

        private Coroutine _coroutine;

        public ICommand StartCoroutineCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                _coroutine = StartCoroutine(EnumeratorTest());
            });
        }

        public ICommand StopCoroutineCommand
        {
            get => new RelayCommand<object>(obj =>
            {
                StopCoroutine(_coroutine);
            });
        }


        private IEnumerator EnumeratorTest()
        {
            while (true)
            {
                Console.WriteLine("biu");

                yield return new WaitForSeconds(1);
            }
        }


        #endregion

        ~MainWindowViewModel()
        {
            ExitProcessCommand.Execute(null);
        }


    }
}
